﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Finds end points of skeleton. For example:
    ///1  0  0  0           1  0  0  0
    ///0  1  0  0  becomes  0  0  0  0
    ///0  0  1  0           0  0  1  0
    ///0  0  0  0           0  0  0  0
    /// </summary>
    public class EndPoints : BaseForeBackgroundColorFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EndPoints"/> class.
        /// </summary>
        public EndPoints()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EndPoints"/> class.
        /// </summary>
        /// <param name="_endPoints">The _end points.</param>
        internal EndPoints(EndPoints _endPoints)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            int y = 0;
            int x = 0;
            int nHeight = _bitmap.Height;
            int nWidth = _bitmap.Width;

            Color[] aColor = new Color[8];

            UnsafeBitmap bitmapCloned = (UnsafeBitmap)_bitmap.Clone();

            int nForegroundCount = 0;
            int nBackgroundCount = 0;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    aColor = Segmentation.GetEnvironmentPixelColorArray(bitmapCloned, x, y, Definitions.EnvironmentPointListClockwise, aColor);

                    Color color = _bitmap.GetPixel(x,y);
                    nForegroundCount = 0;
                    nBackgroundCount = 0;
                    foreach (Color colorEnvironment in aColor)
                    {
                        if (colorEnvironment == m_ColorForeground)
                        {
                            nForegroundCount++;
                        }
                        if (colorEnvironment == m_ColorBackground)
                        {
                            nBackgroundCount++;
                        }
                    }
                    _bitmap.SetPixel(x, y, nForegroundCount == 2 && nBackgroundCount == 6 && color == m_ColorForeground ? m_ColorForeground : m_ColorBackground);
                }
            }
            bitmapCloned.Dispose();
            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new EndPoints(this);
        }
    }
}
